from django.db import models
from users.models import User
from merchants.models import Merchant, MenuItem

class Order(models.Model):
    STATUS_CHOICES = [
        ('pending', '待接单'),
        ('accepted', '已接单'),
        ('preparing', '准备中'),
        ('delivering', '配送中'),
        ('completed', '已完成'),
        ('cancelled', '已取消'),
    ]
    
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='用户')
    merchant = models.ForeignKey(Merchant, on_delete=models.CASCADE, verbose_name='商家')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending', verbose_name='订单状态')
    total_amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='订单总额')
    delivery_address = models.TextField(verbose_name='配送地址')
    delivery_phone = models.CharField(max_length=11, verbose_name='联系电话')
    remarks = models.TextField(blank=True, verbose_name='备注')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        verbose_name = '订单'
        verbose_name_plural = verbose_name
        ordering = ['-created_at']
        
    def __str__(self):
        return f"订单{self.id} - {self.user.username}"

class OrderItem(models.Model):
    order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE, verbose_name='订单')
    menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE, verbose_name='菜品')
    quantity = models.IntegerField(default=1, verbose_name='数量')
    price = models.DecimalField(max_digits=8, decimal_places=2, verbose_name='价格')
    
    class Meta:
        verbose_name = '订单项'
        verbose_name_plural = verbose_name
        
    def __str__(self):
        return f"{self.order.id} - {self.menu_item.name} x {self.quantity}"
